/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.sharding.client.util;

import java.util.ArrayList;
import java.util.List;

public class Page<E> extends ArrayList<E> {

    private int start;
    /**
     * 页码，从1开始
     */
    private int pageNum;

    /**
     * 总页数
     */
    private int pages;

    /**
     * 页面大小
     */
    private int pageSize;

    private long total;

    /**
     * 排序
     */
    private String orderBy;

    public Page(int pageNum, int pageSize) {
        super(0);
        this.pageSize = pageSize;
        this.pageNum = pageNum;
        this.start = (pageNum - 1) * this.pageSize;
    }

    public Page(int pageNum, int pageSize,String orderBy) {
        super(0);
        this.pageSize = pageSize;
        this.pageNum = pageNum;
        this.start = (pageNum - 1) * this.pageSize;
        this.orderBy = orderBy;
    }

    public String getOrderBy() {
        return orderBy;
    }

    public <E> Page<E> setOrderBy(String orderBy) {
        this.orderBy = orderBy;
        return (Page<E>) this;
    }

    public int getPages() {
        return pages;
    }

    public Page<E> setPages(int pages) {
        this.pages = pages;
        return this;
    }

    public int getPageNum() {
        return pageNum;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
        if (total == -1) {
            pages = 1;
            return;
        }
        if (pageSize > 0) {
            pages = (int) (total / pageSize + ((total % pageSize == 0) ? 0 : 1));
        } else {
            pages = 0;
        }
    }

    public int getStart() {
        return start;
    }

    public int getPageSize() {
        return pageSize;
    }


    public Page<E> page(List<E> result) {
        if (result.size() >= this.getStart()) {
            int end = this.getStart() + this.getPageSize();
            if (end > result.size()) {
                end = result.size();
            }
            result = new ArrayList<>(result.subList(this.getStart(), end));
        } else {
            result = new ArrayList<>();
        }
        this.addAll(result);
        return this;
    }
}
